package cmd

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"sale-admin/config/mysql"
	"sale-admin/internal/app/web/schema"
	"sale-admin/internal/app/web/service"
	"sale-admin/internal/app/web/service/common"
	"sale-admin/internal/app/web/service/order"
	"sale-admin/internal/app/web/service/robotinfo"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"sale-admin/internal/define"
	"sale-admin/internal/models"

	"192.168.1.75/go-pkg/helper"
	"github.com/golang-module/carbon"
	"github.com/spf13/cobra"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

// 修复数据的类型
var fixDataType string

func init() {
	rootCmd.PersistentFlags().StringVarP(&fixDataType, "type", "t", "", "fix db data")
	rootCmd.AddCommand(fixDBDataCmd)
}

// 支持的数据处理类型  类型名 => 处理函数
var FixDBDataFunc = map[string]func(arg []string){
	"face_count_date":                       FaceCountDate,
	"goods_click_date":                      GoodsClickDate,
	"physical_info_date":                    PhysicalInfoDate,
	"order_date":                            OrderDate,
	"physical_info_robot_name":              PhysicalInfoRobotName,
	"sales_info_robot_name":                 SalesInfoRobotName,
	"wechat_rate_robot_name":                WechatRateRobotName,
	"order_refund_robot_name":               OrderRefundRobotName,
	"robot_daily_report_data":               RobotDailyReportData,
	"robot_daily_report_task":               RobotDailyReportTask,
	"robot_daily_report_location":           RobotDailyReportLocation,
	"robot_daily_report_order":              RobotDailyReportOrder,
	"robot_daily_report_transaction_amount": RobotDailyReportTransactionAmount,
	"robot_daily_report_facecount":          RobotDailyReportFacecount,
	"robot_daily_report_starecount":         RobotDailyReportStarecount,
	"goods_daily_report_data":               GoodsDailyReportData,
	"goods_daily_report_order":              GoodsDailyReportOrder,
	"goods_daily_report_goods_click":        GoodsDailyReportGoodsClick,
	"robot_empty_stock":                     RobotEmptyStock,
	"robot_empty_stock_log":                 RobotEmptyStockLog,
	"robot_inventory":                       RobotInventory,
	"face_count_migrate":                    FaceCountMigrate,
	"backfill_order_goods_id":               BackfillOrderGoodsID,
	"fix_order_add_time":                    FixOrderAddTime,
	"payment_merge":                         PaymentMerge,
}

// 数据库数据临时修复脚本
var fixDBDataCmd = &cobra.Command{
	Use:   "fixdb",
	Short: "fixdb",
	Run: func(c *cobra.Command, arg []string) {
		startTime := time.Now()
		if _, ok := FixDBDataFunc[fixDataType]; ok {
			FixDBDataFunc[fixDataType](arg)
		} else {
			fmt.Println("未知的类型")
		}
		usedTime := time.Since(startTime)
		fmt.Println("输入参数arg:", "fixdb -t", fixDataType, strings.Join(arg, " "))
		fmt.Println("修复数据全程耗时:", usedTime)
	},
}

// 将传入的起止时间参数转换为时间戳
func HandleTimeArg(arg []string) (start, end int64) {
	if len(arg) != 2 {
		panic("请选择开始时间及结束时间!")
	}
	start = carbon.ParseByLayout(arg[0], carbon.DateLayout).Timestamp()
	end = carbon.ParseByLayout(arg[1], carbon.DateLayout).EndOfDay().Timestamp()
	return
}

// 曝光表处理created_date字段填充start_time的值
func FaceCountDate(arg []string) {
	db := mysql.NewDB()
	db.Model(&models.MaAIServiceFaceCount{}).
		Where("start_time <= '2023-01-01'").
		UpdateColumn("created_date", gorm.Expr("`start_time`"))
	db.Model(&models.MaAIServiceFaceCount{}).
		Where("start_time > '2023-01-01' and start_time <= '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`start_time`"))
	db.Model(&models.MaAIServiceFaceCount{}).
		Where("start_time > '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`start_time`"))
}

// 商品点击量表写入日期created_date
func GoodsClickDate(arg []string) {
	db := mysql.NewDB()
	db.Model(&models.MaGoodsClick{}).
		Where("start_time <= '2023-01-01'").
		UpdateColumn("created_date", gorm.Expr("`start_time`"))
	db.Model(&models.MaGoodsClick{}).
		Where("start_time > '2023-01-01' and start_time <= '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`start_time`"))
	db.Model(&models.MaGoodsClick{}).
		Where("start_time > '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`start_time`"))
}

// 用户画像表写入日期created_date
func PhysicalInfoDate(arg []string) {
	db := mysql.NewDB()
	db.Model(&models.MaPhysicalInfo{}).
		Where("add_time <= '2023-01-01'").
		UpdateColumn("created_date", gorm.Expr("`add_time`"))
	db.Model(&models.MaPhysicalInfo{}).
		Where("add_time > '2023-01-01' and add_time <= '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`add_time`"))
	db.Model(&models.MaPhysicalInfo{}).
		Where("add_time > '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`add_time`"))
}

// 订单表写入日期created_date
func OrderDate(arg []string) {
	db := mysql.NewDB()
	db.Model(&models.MaOrder{}).
		Where("add_time <= '2023-01-01'").
		UpdateColumn("created_date", gorm.Expr("`add_time`"))
	db.Model(&models.MaOrder{}).
		Where("add_time > '2023-01-01' and add_time <= '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`add_time`"))
	db.Model(&models.MaOrder{}).
		Where("add_time > '2023-07-01'").
		UpdateColumn("created_date", gorm.Expr("`add_time`"))
}

// 补货表sales_info写入robot_name
func SalesInfoRobotName(arg []string) {
	db := mysql.NewDB()
	if !db.Migrator().HasColumn(&models.MaRobotSalesInfo{}, "robot_name") {
		db.Migrator().AddColumn(&models.MaRobotSalesInfo{}, "robot_name")
	}
	var robotList []models.MaRobot
	db.Model(&models.MaRobot{}).Find(&robotList)
	for _, v := range robotList {
		db.Model(&models.MaRobotSalesInfo{}).
			Where("sales_id = ?", v.SalesID).
			UpdateColumn("robot_name", v.RobotName)
	}
}

// 人流量表写入robot_name
func PhysicalInfoRobotName(arg []string) {
	db := mysql.NewDB()
	if !db.Migrator().HasColumn(&models.MaPhysicalInfo{}, "robot_name") {
		db.Migrator().AddColumn(&models.MaPhysicalInfo{}, "robot_name")
	}
	var robotList []models.MaRobot
	db.Model(&models.MaRobot{}).Find(&robotList)
	for _, v := range robotList {
		db.Model(&models.MaPhysicalInfo{}).
			Where("sales_id = ?", v.SalesID).
			UpdateColumn("robot_name", v.RobotName)
	}
}

// wechat_rate表写入robot_name
func WechatRateRobotName(arg []string) {
	db := mysql.NewDB()
	if !db.Migrator().HasColumn(&models.MaWechatRate{}, "robot_name") {
		db.Migrator().AddColumn(&models.MaWechatRate{}, "robot_name")
	}
	var robotList []models.MaRobot
	db.Model(&models.MaRobot{}).Find(&robotList)
	for _, v := range robotList {
		db.Model(&models.MaWechatRate{}).
			Where("sales_id = ?", v.SalesID).
			UpdateColumn("robot_name", v.RobotName)
	}
}

// 订单退款表写入robot_name
func OrderRefundRobotName(arg []string) {
	db := mysql.NewDB()
	if !db.Migrator().HasColumn(&models.MaOrderRefund{}, "robot_name") {
		db.Migrator().AddColumn(&models.MaOrderRefund{}, "robot_name")
	}
	var robotList []models.MaRobot
	db.Model(&models.MaRobot{}).Find(&robotList)
	for _, v := range robotList {
		db.Model(&models.MaOrderRefund{}).
			Where("sales_id = ?", v.SalesID).
			UpdateColumn("robot_name", v.RobotName)
	}
}

// 机器日报表处理数据【全部数据】
func RobotDailyReportData(arg []string) {
	service.RobotDailyReport{}.FixData(HandleTimeArg(arg))
}

// 机器日报表处理任务数据
func RobotDailyReportTask(arg []string) {
	service.RobotDailyReport{}.FixTask(HandleTimeArg(arg))
}

// 机器日报表处理定位location
func RobotDailyReportLocation(arg []string) {
	service.RobotDailyReport{}.FixRobotLocation(HandleTimeArg(arg))
}

// 机器日报表处理订单数据
func RobotDailyReportOrder(arg []string) {
	service.RobotDailyReport{}.FixRobotOrder(HandleTimeArg(arg))
}

// 机器日报表处理交易金额
func RobotDailyReportTransactionAmount(arg []string) {
	service.RobotDailyReport{}.FixRobotTransactionAmount(HandleTimeArg(arg))
}

// 机器日报表处理曝光量
func RobotDailyReportFacecount(arg []string) {
	service.RobotDailyReport{}.FixRobotFacecount(HandleTimeArg(arg))
}

// 机器日报表处理凝视
func RobotDailyReportStarecount(arg []string) {
	service.RobotDailyReport{}.FixRobotStarecount(HandleTimeArg(arg))
}

// 商品日报表处理数据【订单 + 商品点击量】
func GoodsDailyReportData(arg []string) {
	service.GoodsDailyReport{}.FixData(HandleTimeArg(arg))
}

// 商品日报表处理订单数据
func GoodsDailyReportOrder(arg []string) {
	service.GoodsDailyReport{}.FixGoodsOrder(HandleTimeArg(arg))
}

// 商品日报表处理商品点击量
func GoodsDailyReportGoodsClick(arg []string) {
	service.GoodsDailyReport{}.FixGoodsClick(HandleTimeArg(arg))
}

// 商品空货合并表
func RobotEmptyStock(arg []string) {
	start, end := HandleTimeArg(arg)
	// 处理单日空货
	db := mysql.NewDB()
	var insertSingleData []models.MaRobotInventoryZeroSingel
	db.Model(&models.MaRobotInventoryZeroSingel{}).
		Where("date between ? and ?", carbon.CreateFromTimestamp(start).ToDateString(), carbon.CreateFromTimestamp(end).ToDateString()).
		Find(&insertSingleData)
	for _, v := range insertSingleData {
		// 删除旧数据
		db.Where("type = 1").
			Where("date = ? and robot_name = ?", v.Date, v.RobotName).
			Where("merchant_id = ? and goods_id = ?", v.ShopID, v.GoodsID).
			Delete(&models.MaRobotEmptyStock{})
		// 写入新数据
		var insert models.MaRobotEmptyStock
		insert.ID, _ = helper.UUID{}.String()
		insert.Type = 1
		insert.MerchantID = v.ShopID
		insert.RobotName = v.RobotName
		insert.Date = time.Time(v.Date).Format("2006-01-02")
		insert.GoodsID = v.GoodsID
		insert.GoodsInventory = v.GoodsInventory
		insert.GoodsMaxInventory = v.GoodsMaxInventory
		insert.CreatedAt = time.Now().Unix()
		db.Create(&insert)
	}
	// 处理连续空货
	var insertContinueData []models.MaRobotInventoryZeroContinue
	db.Model(&models.MaRobotInventoryZeroContinue{}).
		Where("date between ? and ?", carbon.CreateFromTimestamp(start).ToDateString(), carbon.CreateFromTimestamp(end).ToDateString()).
		Find(&insertContinueData)
	for _, v := range insertContinueData {
		// 删除旧数据
		db.Where("type = 2").
			Where("date = ? and robot_name = ?", v.Date, v.RobotName).
			Where("merchant_id = ? and goods_id = ?", v.ShopID, v.GoodsID).
			Delete(&models.MaRobotEmptyStock{})
		// 写入新数据
		var insert models.MaRobotEmptyStock
		insert.ID, _ = helper.UUID{}.String()
		insert.Type = 2
		insert.MerchantID = v.ShopID
		insert.RobotName = v.RobotName
		insert.Date = time.Time(v.Date).Format("2006-01-02")
		insert.GoodsID = v.GoodsID
		insert.GoodsInventory = v.GoodsInventory
		insert.GoodsMaxInventory = v.GoodsMaxInventory
		insert.CreatedAt = time.Now().Unix()
		db.Create(&insert)
	}
}
func RobotEmptyStockLog(arg []string) {
	start, end := HandleTimeArg(arg)

	db := mysql.NewDB()
	var zeroStockLog []models.MaRobotReportZeroStockLog
	db.Model(&models.MaRobotReportZeroStockLog{}).
		Where("created_at between ? and ?", start, end).
		Find(&zeroStockLog)
	for _, v := range zeroStockLog {
		var logType int
		if v.ZeroType == 1 { // 4单日空货
			logType = 4
		} else if v.ZeroType == 2 { // 5连续空货
			logType = 5
		}
		// 删除旧数据
		db.Where("type = ?", logType).
			Where("url = ? and object = ?", v.Url, v.Object).
			Where("start_time = ? and end_time = ?", v.StartTime, v.EndTime).
			Delete(&models.MaRobotReportLog{})
		// 写入新数据
		var insert models.MaRobotReportLog
		insert.ID, _ = helper.UUID{}.String()
		insert.Url = v.Url
		insert.Type = logType
		insert.RobotName = v.RobotName
		insert.ObjectName = v.ObjectName
		insert.WebHookName = v.WebHookName
		insert.WebHookAddress = v.WebHookUrl
		insert.Object = v.Object
		insert.StartTime = v.StartTime
		insert.EndTime = v.EndTime
		insert.AddTime = v.AddTime
		insert.CreatedAt = time.Now().Unix()
		db.Create(&insert)
	}
}

func RobotInventory(arg []string) {
	db := mysql.NewDB()
	if len(arg) != 2 {
		panic("请选择开始时间及结束时间!")
	}
	dayList := common.GetPeriodsByType(arg[0], arg[1], define.DAY)
	// 日期，机器，商品
	// thisDay 要统计的日期
	// statisticTime 库存定时统计的时间：次日两点
	for _, thisDay := range dayList { // 日期
		statisticTime := carbon.Parse(thisDay).AddDay().ToDateString() + " 02:00:00" // 库存定时任务为第二日的2点
		rList, rCount, _ := dao.Robot{}.RobotList(context.Background(), db, "", thisDay, "", "", "", "", "", "")
		if rCount == 0 {
			continue
		}
		var batchInsert []models.MaRobotInventory
		for _, robot := range rList { // 机器
			if robot.SalesID == "" {
				continue
			}
			// 机器关联的商品及最大库存
			var goodsInventory []struct {
				GoodsID           int64 `gorm:"column:goods_id"`
				GoodsMaxInventory int64 `gorm:"column:goods_max_inventory"`
			}
			db.Model(&models.MaRobotSalesInfo{}).
				Where("sales_id = ?", robot.SalesID).
				Where("container_status = 1 and container_use_status = 1"). // 上架 + 正常
				Group("goods_id").
				Select("goods_id", "sum(goods_max_inventory) as goods_max_inventory").
				Find(&goodsInventory)
			// 获取故障货道信息
			errorContainerNum, zeroContainerNum, _ := robotinfo.RobotInfoService{}.
				GetHistoryErrorContainerNums(context.Background(), dal.Q, robot.SalesID)
			for _, inventoryInfo := range goodsInventory { // 商品
				// 补货记录
				var saleInfoDetail models.MaSaleInfoLogDetail
				logDetailRow := db.Model(&models.MaSaleInfoLogDetail{}).
					Where("sales_id = ?", robot.SalesID).
					Where("goods_id = ?", inventoryInfo.GoodsID).
					Where("add_time <= ?", statisticTime).
					Order("add_time desc").
					First(&saleInfoDetail).RowsAffected
				if logDetailRow <= 0 {
					continue
				}
				// 最后补货时间以来的成功订单 [机器 + 日期 => 订单号]
				var outTradeNoList []string
				db.Model(&models.MaOrder{}).
					Where("sales_id = ? AND order_status = 4", robot.SalesID). // 出货成功
					Where("add_time between ? AND ?", saleInfoDetail.AddTime, thisDay+" 23:59:59").
					Pluck("out_trade_no", &outTradeNoList)
				// 订单信息【订单号 + 商品 => 商品销售量】
				var saleGoodsCount = struct {
					Sum int64
				}{}
				if len(outTradeNoList) > 0 {
					db.Model(&models.MaOrderGoods{}).
						Where("out_trade_no in (?)", outTradeNoList).
						Where("goods_id = ?", inventoryInfo.GoodsID).
						Select("count(*) as sum").
						Take(&saleGoodsCount)
				}

				// 处理库存表数据
				var insert models.MaRobotInventory
				insert.RobotName = robot.RobotName
				insert.Date = datatypes.Date(carbon.Parse(thisDay).ToStdTime())
				insert.SalesID = robot.SalesID
				insert.ShopID = robot.MerchantID
				insert.Areas3 = strconv.Itoa(robot.Areas3)
				insert.GoodsID = inventoryInfo.GoodsID
				insert.GoodsInventory = int64(saleInfoDetail.LastNum) - saleGoodsCount.Sum
				insert.GoodsMaxInventory = int64(inventoryInfo.GoodsMaxInventory)
				insert.ErrorContainerNum = errorContainerNum
				insert.ZeroContainerNum = zeroContainerNum // 累加0库存货道，逗号隔开
				batchInsert = append(batchInsert, insert)
			}
		}
		if len(batchInsert) > 0 {
			db.Model(&models.MaRobotInventory{}).CreateInBatches(batchInsert, 100)
		}
	}
}
func FaceCountMigrate(arg []string) {
	db := mysql.NewDB()
	// 调整字段
	if db.Migrator().HasColumn(&models.MaAIServiceFaceCount{}, "add_time") {
		db.Migrator().DropColumn(&models.MaAIServiceFaceCount{}, "add_time")
	}
	if db.Migrator().HasColumn(&models.MaAIServiceFaceCount{}, "new_start_time") {
		db.Migrator().DropColumn(&models.MaAIServiceFaceCount{}, "new_start_time")
	}
	if db.Migrator().HasColumn(&models.MaAIServiceFaceCount{}, "new_end_time") {
		db.Migrator().DropColumn(&models.MaAIServiceFaceCount{}, "new_end_time")
	}
	if db.Migrator().HasColumn(&models.MaAIServiceFaceCount{}, "sales_id") {
		db.Migrator().DropColumn(&models.MaAIServiceFaceCount{}, "sales_id")
	}
	if db.Migrator().HasColumn(&models.MaAIServiceFaceCount{}, "face_count") {
		db.Migrator().DropColumn(&models.MaAIServiceFaceCount{}, "face_count")
	}
	db.Migrator().AlterColumn(&models.MaAIServiceFaceCount{}, "merchant_id")

	// 删除索引
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "AddTime") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "AddTime")
	}
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "created_at") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "created_at")
	}
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "RobotName") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "RobotName")
	}
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "idx_starttime_salesid") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "idx_starttime_salesid")
	}
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "idx_starttime_facecount0_facecount1_facecount2") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "idx_starttime_facecount0_facecount1_facecount2")
	}
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "idx_starttime_merchant") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "idx_starttime_merchant")
	}
	if db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "idx_createdDate_robotName") {
		db.Migrator().DropIndex(&models.MaAIServiceFaceCount{}, "idx_createdDate_robotName")
	}
	// 新增索引
	if !db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "idx_createdDate_robotName") {
		db.Migrator().CreateIndex(&models.MaAIServiceFaceCount{}, "idx_createdDate_robotName")
	}
	if !db.Migrator().HasIndex(&models.MaAIServiceFaceCount{}, "idx_startTime_robotName") {
		db.Migrator().CreateIndex(&models.MaAIServiceFaceCount{}, "idx_startTime_robotName")
	}
}

// BackfillOrderGoodsID 回填订单表的商品id
func BackfillOrderGoodsID(arg []string) {
	startTime, endTime := HandleTimeArg(arg)
	order.OrderDataFix{}.BackfillGoodsID(context.Background(), startTime, endTime)
}

// BackfillOrderGoodsID 回填订单表的商品id
func FixOrderAddTime(arg []string) {
	startTime, endTime := HandleTimeArg(arg)
	order.OrderDataFix{}.FixOrderAddTime(context.Background(), startTime, endTime)
}

func PaymentMerge(arg []string) {
	db := mysql.NewDB()
	// 清空ma_payment
	db.Model(&models.MaPayment{}).Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&models.MaPayment{})
	db.Exec("ALTER TABLE ma_payment AUTO_INCREMENT = 1;")

	// ma_payment_alipay
	var aliPayList []schema.PaymentAlipayRsp
	db.Table("ma_payment_alipay").Where("deleted = 0").Find(&aliPayList)
	for _, v := range aliPayList {
		config := schema.PaymentAlipay{
			AliPayAppID:      v.AliPayAppID,
			AliPayPrivateKey: v.AliPayPrivateKey,
		}
		configBytes, _ := json.Marshal(config)
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_Alipay,
			v.ID, v.Name, string(configBytes))
	}
	// ma_payment_dx
	var dxPayList []schema.PaymentDxRsp
	db.Table("ma_payment_dx").Where("deleted = 0").Find(&dxPayList)
	for _, v := range dxPayList {
		config := schema.PaymentDx{
			DxAppID:      v.DxAppID,
			DxAppKey:     v.DxAppKey,
			DxSellerID:   v.DxSellerID,
			DxMerchantID: v.DxMerchantID,
			DxShopID:     v.DxShopID,
		}
		configBytes, _ := json.Marshal(config)
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_DaXing,
			v.ID, v.Name, string(configBytes))
	}
	// ma_payment_jh
	var jhPayList []schema.PaymentJhRsp
	db.Table("ma_payment_jh").Where("deleted = 0").Find(&jhPayList)
	for _, v := range jhPayList {
		config := schema.PaymentJh{
			JhMerchantNum: v.JhMerchantNum,
			JhApiKey:      v.JhApiKey,
		}
		configBytes, _ := json.Marshal(config)
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_JuHe,
			v.ID, v.Name, string(configBytes))
	}
	// ma_payment_pos
	var posPayList []schema.PaymentPosRsp
	db.Table("ma_payment_pos").Where("deleted = 0").Find(&posPayList)
	for _, v := range posPayList {
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_POS,
			v.ID, v.Name, "")
	}
	// ma_payment_small
	var smallPayList []schema.PaymentSmallRsp
	db.Table("ma_payment_small").Where("deleted = 0").Find(&smallPayList)
	for _, v := range smallPayList {
		config := schema.PaymentWechat{
			WeChatMchID:  v.WeChatMchID,
			WeChatAppID:  v.WeChatAppID,
			WeChatAppKey: v.WeChatAppKey,
			CertFile:     v.CertFile,
		}
		configBytes, _ := json.Marshal(config)
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_XiaoTianCai,
			v.ID, v.Name, string(configBytes))
	}
	// ma_payment_stripe
	var stripePayList []schema.PaymentStripeRsp
	db.Table("ma_payment_stripe").Where("deleted = 0").Find(&stripePayList)
	for _, v := range stripePayList {
		config := schema.PaymentStripe{
			StripePrivKey: v.StripePrivKey,
			StripePubKey:  v.StripePubKey,
		}
		configBytes, _ := json.Marshal(config)
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_Stripe,
			v.ID, v.Name, string(configBytes))
	}
	// ma_payment_wechat
	var wechatPayList []schema.PaymentWechatRsp
	db.Table("ma_payment_wechat").Where("deleted = 0").Find(&wechatPayList)
	for _, v := range wechatPayList {
		config := schema.PaymentWechat{
			WeChatMchID:  v.WeChatMchID,
			WeChatAppID:  v.WeChatAppID,
			WeChatAppKey: v.WeChatAppKey,
			CertFile:     v.CertFile,
		}
		configBytes, _ := json.Marshal(config)
		dao.Payment{}.Create(context.Background(), dal.Q, v.ShopID, define.PaymentType_Wechat,
			v.ID, v.Name, string(configBytes))
	}
}
